package com.github.ldw4033.activiti.ch05.controller;

import com.github.ldw4033.activiti.ch05.ActivitiUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * Created by dw.liu on 2015/8/21 0021.
 */
@Controller
@RequestMapping(value = "/deployment")
public class DeploymentController {
    private static final Logger log = LoggerFactory.getLogger(DeploymentController.class);

    private ProcessEngine processEngine = ActivitiUtils.getProcessEngine();


    @RequestMapping(value = "/processList")
    public String list(Model model) {
        RepositoryService repositoryService = processEngine.getRepositoryService();

        List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery().list();

        model.addAttribute("processDefinitionList", processDefinitionList);

        return "processList";
    }

    @RequestMapping(value = "/deploy")
    public String deploy(@RequestParam(value = "file", required = true) MultipartFile file) {

        RepositoryService repositoryService = processEngine.getRepositoryService();

        String filename = file.getOriginalFilename();
        String fileExtension = FilenameUtils.getExtension(filename);

        try {
            InputStream inputStream = file.getInputStream();
            DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();

            if (StringUtils.equals(fileExtension, "bar") || StringUtils.equals(fileExtension, "zip")) {
                deploymentBuilder.addZipInputStream(new ZipInputStream(inputStream));
            } else {
                deploymentBuilder.addInputStream(filename, inputStream);
            }
            deploymentBuilder.deploy();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/deployment/processList";
    }

    @RequestMapping(value = "readResource")
    public void readResource(@RequestParam(value = "pdid") String processDefinitionId,
                             String resourceName,
                             HttpServletResponse response) {
        log.debug("processDefinitionId：{}", processDefinitionId);
        log.debug("resourceName：{}", resourceName);


        RepositoryService repositoryService = processEngine.getRepositoryService();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId)
                .singleResult();

        if(processDefinition==null){
            throw  new RuntimeException("没有对应的流程定义");
        }


        InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);

        byte[] b = new byte[1024];
        int len = -1;

        try {
            while ((len = inputStream.read(b, 0, 1024)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    @RequestMapping(value = "delete")
    public String delete(@RequestParam(value = "deploymentId")String deploymentId){

        RepositoryService repositoryService=processEngine.getRepositoryService();
        repositoryService.deleteDeployment(deploymentId, Boolean.TRUE);

        return "redirect:processList";
    }

}
